﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ImageHandler;
using Stamp_For_Africa_Version_2.Models;
using Stamp_For_Africa_Version_2.Repositories;

namespace Stamp_For_Africa_Version_2.Controllers
{
  public class WatermarkController : Controller
  {
    //
    // GET: /Watermark/
    WatermarkRepository _watermarkRepository = new WatermarkRepository();
    public ActionResult Index()
    {
      List<Watermark> watermarks = _watermarkRepository.FindAllWatermarks().ToList();
      return View(watermarks);
    }

    [Authorize]
    public ActionResult Create()
    {
      Watermark watermark = new Watermark();

      watermark.NonRootedUploadedFileName = "../../Content/images/unknown.png";
      var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(watermark.NonRootedUploadedFileName));
      watermark.UploadedFileName = fileName;

      return View(watermark);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Watermark watermark)
    {
      watermark.Id = Guid.NewGuid();

      //Save temp image features
      Byte[] fileBytes = FileImagePersistence.ReadFileBytes(watermark.UploadedFileName);
      watermark.Image = fileBytes;

      _watermarkRepository.Add(watermark);
      return RedirectToAction("Details", new {id = watermark.Id});
    }

    public ActionResult Details(Guid id)
    {
      Watermark watermark = _watermarkRepository.GetWatermark(id);
      return View(watermark);
    }

    public ActionResult Edit(Guid id)
    {
      Watermark watermark = _watermarkRepository.GetWatermark(id);
      return View(watermark);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Guid id, FormCollection formCollection)
    {
      Watermark watermark = _watermarkRepository.GetWatermark(id);
      UpdateModel(watermark);
      return RedirectToAction("Details", new {id = id});
    }


		[Authorize]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult FileUpload(WatermarkImageUploadModel uploadedFileMeta)
		{

			try
			{
				var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(uploadedFileMeta.fileData.FileName));
				var nonRootedPath = "/uploads/" + System.IO.Path.GetFileName(uploadedFileMeta.fileData.FileName);
				uploadedFileMeta.fileData.SaveAs(fileName);
				return Json(new { Status = "OK", returnFile = fileName, serverPath = nonRootedPath });
			}
			catch (Exception ex)
			{
				return Json(new { Status = "Failed" });
			}

		}

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult ShowWatermark(Guid id)
    {
      
      Watermark watermark = _watermarkRepository.GetWatermark(id);
      if (watermark != null)
        return File(watermark.Image.ToArray(), "image/jpg");
      else
      {
        return null;
      }
    }

  }
}
